package vn.sunnet.backviet01.game.coloa.util.mypool;

import java.util.ArrayList;

public abstract class MyGenericPoolSprite<T> {
	protected final ArrayList<T> freeObjects;
	
	protected int max;
	protected int mAvailableRecycle;
	
	public MyGenericPoolSprite() {
		this(0);
	}

	public MyGenericPoolSprite(final int pInitialSize) {
		this(pInitialSize, Integer.MAX_VALUE);
	}

	public MyGenericPoolSprite(final int pInitialSize, final int pAvailableItemsMaximum) {
		freeObjects = new ArrayList<T>(pInitialSize);
		max = pAvailableItemsMaximum;
		mAvailableRecycle = 0;
	}
	
	public abstract T newObject();
	
	public abstract void onRecycleObject(final T object);
	
	public abstract void onClearPool();
	
	public void free(final T object) {
		if (object == null) throw new IllegalArgumentException("object cannot be null.");
		if (freeObjects.size() < max) {
			onRecycleObject(object);
			freeObjects.add(object);
			mAvailableRecycle++;
		}
	}
	
	public T obtain() {
		T object;
		
		if (mAvailableRecycle == 0)
			object = newObject();
		else {
			object = pop();
		}
		
		return object;
	}
	
	private T pop() {
		T object = null;
		--mAvailableRecycle;
		
		object = freeObjects.get(mAvailableRecycle);
		
		freeObjects.remove(mAvailableRecycle);
		
		return object;
	}
	
	public void clear() {
		freeObjects.clear();
	}
	
	public int size() {
		return mAvailableRecycle;
	}
}
